<template>
  <div class="main">
    <div>
      <a-space direction="vertical" class="abc">
        <a-input-search
          v-model:value="value"
          placeholder="搜索文章标题"
          enter-button
          @search="onSearch"
        />
      </a-space>
      <a-button @click="btnAllFn">显示所有</a-button>
    </div>
    <table>
      <thead>
        <tr>
          <th class="th1">标题</th>
          <th class="th2">内容</th>
          <th class="th3">作者</th>
          <th class="th4">操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in state" :key="item.id">
          <td @click="detail(item.id)">{{ item.title }}</td>
          <td>
            {{ item.content ? item.content.slice(0, 60) : "" }}<span>...</span>
          </td>

          <td>{{ item.author }}</td>
          <td>
            <a-button type="primary" @click="deleteItem(item.id)"
              >删除</a-button
            >
            <a-button type="primary" @click="updateFn">修改</a-button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { showPassageApi, deletePassageApi, searchApi } from "../utils/api";
// 引入路由跳转详情
import { useRouter } from "vue-router";
const router = useRouter();

const state = ref({});

const data = async () => {
  const res = await showPassageApi();
  // 将过滤后的数据添加到state中
  res.data.forEach((item) => {
    // 过滤数据is_deleted为1的数据
    if (item.is_deleted === 0) {
      state.value[item.id] = item;
    }
  });
};
data();

// 点击title跳转详情
const detail = (id) => {
  console.log(id);
  router.push(`/detail/${id}`);
};

// 点击删除按钮，删除当前行，同时删除数据库中的数据
const deleteItem = async (id) => {
  const res = confirm("是否确定删除");
  if (!res) return;
  await deletePassageApi({ id: id }).then((res) => {
    console.log(res);
  });
  delete state.value[id];
};

const onSearch = (searchValue) => {
  searchApi({ searchValue }).then((res) => {
    console.log(res.data[0]);
    state.value = {};
    state.value[res.data[0].id] = res.data[0];
  });
};

// 显示所有数据
const btnAllFn = () => {
  console.log("显示所有数据");
  // 重新获取数据
  data();
  //清空搜索框
  value.value = "";
};
</script>

<style lang="less" scoped>
.main {
  cursor: pointer;
  table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
    th {
      background-color: #f5f5f5;
      font-weight: bold;
      text-align: center;
      padding: 10px;
      border: 1px solid #ddd;
    }
    td {
      text-align: center;
      padding: 10px;
      border: 1px solid #ddd;
    }
    .th1 {
      width: 20%;
    }
    .th2 {
      width: 55%;
    }
    .th3 {
      width: 10%;
      // 字体向左对齐
      text-align: left;
    }
    .th4 {
      width: 15%;
    }
  }
}
</style>
